package com.ziyun.erp.modules.goodsCopyNew.service.impl;

import com.utility.New;
import com.ziyun.erp.modules.goods.entity.GoodsEntity;
import com.ziyun.erp.modules.goods.entity.GoodsOptionEntity;
import com.ziyun.erp.modules.goods.entity.GoodsProductEntity;
import com.ziyun.erp.modules.goods.service.GoodsProductService;
import com.ziyun.erp.modules.goods.service.GoodsService;
import com.ziyun.erp.modules.goodsCopyNew.dto.GoodsCopyDto;
import com.ziyun.erp.modules.goodsImage.service.GoodsImageService;
import com.ziyun.erp.modules.goodsProductCopyNew.entity.GoodsProductCopyNewEntity;
import com.ziyun.erp.modules.productBaseInfo.entity.ProductBaseInfoEntity;
import com.ziyun.erp.modules.productBaseInfo.service.ProductBaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.ziyun.erp.modules.goodsCopyNew.dao.GoodsCopyNewDao;
import com.ziyun.erp.modules.goodsCopyNew.entity.GoodsCopyNewEntity;
import com.ziyun.erp.modules.goodsCopyNew.service.GoodsCopyNewService;
import org.springframework.transaction.annotation.Transactional;


@Service("goodsCopyNewService")
public class GoodsCopyNewServiceImpl extends ServiceImpl<GoodsCopyNewDao, GoodsCopyNewEntity> implements GoodsCopyNewService {

    private Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");// 匹配字符串中的img标签

    private Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");// 匹配图片的地址

    @Autowired
    private GoodsImageService goodsImageService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsProductService goodsProductService;
    @Autowired
    private ProductBaseInfoService productBaseInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<GoodsCopyNewEntity> page = this.selectPage(
                new Query<GoodsCopyNewEntity>(params).getPage(),
                new EntityWrapper<GoodsCopyNewEntity>()
        );

        return new PageUtils(page);
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public List<GoodsCopyNewEntity> dataMigration() {
        List<GoodsCopyNewEntity> goodsCopyNewList = this.baseMapper.selectAllGoodsCopy();
        List<Long> successGoodsIds = New.arrayList();
        List<Long> errGoodsIds = New.arrayList();
        List<List<String>> urlTemp = New.arrayList();
        List<List<String>> srcTemp = New.arrayList();
        for(int i = 0;i < goodsCopyNewList.size();i++){
            try{
                //在此对商品数据做控制
                //获取数据第一步:保存商品信息
                GoodsEntity goodsEntity = loadGoods(goodsCopyNewList.get(i));
                if(goodsEntity == null){
                    errGoodsIds.add(goodsCopyNewList.get(i).getGoodsId());
                    continue;
                }
                //获取数据第二步:保存产品信息,并获得默认sku的选项信息
                Map<String, String> map = New.hashMap();
                List<GoodsProductEntity> goodsProductList = loadGoodsProduct(goodsCopyNewList.get(i),map);
                if(goodsProductList == null || goodsProductList.size() == 0){
                    errGoodsIds.add(goodsCopyNewList.get(i).getGoodsId());
                    continue;
                }
                //获取数据第三步:保存图片信息
                //查询默认图片信息
                List<String> urlList = this.baseMapper.selectGoodsUrls(goodsEntity.getGoodsId());
                //获取详细图片
                List<String> srcList = new ArrayList<>(); // 用来存储获取到的图片地址-->该图片没有名称,人工伪造
                handlerDefaultImage(goodsCopyNewList, i, srcList);
                 //获取数据第四步:建立product_base_info
                List<ProductBaseInfoEntity> productBaseInfoEntities = loadProductBaseInfo(goodsEntity,map);
                if(productBaseInfoEntities == null || productBaseInfoEntities.size() == 0){
                    errGoodsIds.add(goodsCopyNewList.get(i).getGoodsId());
                    continue;
                }
                //保存操作第一步:生成imageUrls
                if(urlList != null && urlList.size()>0){
                    String imageUrls =goodsImageService.handlerInsert(urlList,"image_url",goodsEntity.getGoodsId());
                    goodsEntity.setImageUrls(imageUrls);
                }
                //保存操作第二步:生成infoUrls
                if(srcList != null && urlList.size()>0){
                    String infoUrls = goodsImageService.handlerInsert(srcList, "info_url", goodsEntity.getGoodsId());
                    goodsEntity.setInfoUrls(infoUrls);
                }
                //保存操作第三步:生成spu
                goodsService.insert(goodsEntity);
                //保存操作第四步:生成sku
                goodsProductService.insertBatch(goodsProductList);
                //保存productBaseInfo
                productBaseInfoService.insertBatch(productBaseInfoEntities);
                successGoodsIds.add(goodsCopyNewList.get(i).getGoodsId());
            }catch (Exception e){
                //记录出错id
                errGoodsIds.add(goodsCopyNewList.get(i).getGoodsId());
                e.printStackTrace();
                continue;
            }
        }
        System.out.println("successGoodsIds:"+successGoodsIds.toString());
        System.out.println("errGoodsIds:"+errGoodsIds.toString());
        return null;
    }

    /**
     * 按goodsId处理productBaseInfoList
     * @param goods
     * @return
     */
    private List<ProductBaseInfoEntity> loadProductBaseInfo(GoodsEntity goods,Map<String, String> map) {
        String options = map.get("optionIds");
        //写一个sql查出optionList
        List<GoodsOptionEntity> goodsOptionEntityList = this.baseMapper.getOptionsByGoodsId(goods.getGoodsId());
        //遍历组装productBaseInfo
        List<ProductBaseInfoEntity> productBaseInfoEntityList = New.arrayList();
        if(goodsOptionEntityList != null || goodsOptionEntityList.size() >0){
            for(int i = 0;i<goodsOptionEntityList.size();i++){
                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setGoodsId(goods.getGoodsId());
                productBaseInfoEntity.setCategoryId(goods.getCategoryId());
                productBaseInfoEntity.setAttributeId(goodsOptionEntityList.get(i).getAttributeId().intValue());
                productBaseInfoEntity.setOptionId(goodsOptionEntityList.get(i).getOptionId().intValue());
//                productBaseInfoEntity.setInfluenceCraftType();
                if(options != null){
                    if(goodsOptionEntityList.get(i).getOptionId() != 0){
                        if(options.indexOf(goodsOptionEntityList.get(i).getOptionId().toString()) != -1){
                            //设置为默认
                            productBaseInfoEntity.setWhetherDefault(1);
                        }
                    }
                }else{
                    productBaseInfoEntity.setWhetherDefault(0);
                }
                productBaseInfoEntityList.add(productBaseInfoEntity);
            }
        }
        return productBaseInfoEntityList;
    }

    /**
     * 获取图片信息
     * @param goodsCopyNewList
     * @param i
     * @param srcList
     */
    private void handlerDefaultImage(List<GoodsCopyNewEntity> goodsCopyNewList, int i, List<String> srcList) {
//        Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");// 匹配字符串中的img标签
        Matcher matcher = p.matcher(goodsCopyNewList.get(i).getIntro());
        boolean hasPic = matcher.find();
        if (hasPic == true) {// 判断是否含有图片
            while (hasPic) {// 如果含有图片，那么持续进行查找，直到匹配不到
                String group = matcher.group(2);// 获取第二个分组的内容，也就是 (.*?)匹配到的
//                Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");// 匹配图片的地址
                Matcher matcher2 = srcText.matcher(group);
                if (matcher2.find()) {
                    srcList.add(matcher2.group(3));// 把获取到的图片地址添加到列表中
                }
                hasPic = matcher.find();// 判断是否还有img标签
            }
        }
    }

    /**
     * 数据迁移更具商品生产产品实体
     * @param goodsCopyNewEntity
     * @return
     */
    private List<GoodsProductEntity> loadGoodsProduct(GoodsCopyNewEntity goodsCopyNewEntity,Map<String, String> map) {
        List<GoodsProductEntity> goodsProductList = New.arrayList();
        List<GoodsProductCopyNewEntity> goodsProductCopyNewEntityList = goodsCopyNewEntity.getGoodsProductCopyNewEntityList();
        if(goodsProductCopyNewEntityList != null && goodsProductCopyNewEntityList.size() > 0){
            for(int i = 0;i<goodsProductCopyNewEntityList.size();i++){
                GoodsProductCopyNewEntity goodsProductCopyNew = goodsProductCopyNewEntityList.get(i);
                GoodsProductEntity productEntity = new GoodsProductEntity();
                productEntity.setProductId(goodsProductCopyNew.getProductId().longValue());
                productEntity.setGoodsId(goodsProductCopyNew.getGoodsId());
                productEntity.setMinBuyNum(new BigDecimal(goodsProductCopyNew.getProductMinBuy() == null?0:goodsProductCopyNew.getProductMinBuy()));
//                productEntity.setDefaultProduct(goodsProductCopyNew.getIsDefault() == 1?true:false);
                if(goodsProductCopyNew.getIsDefault() != null  && goodsProductCopyNew.getIsDefault() == 1){
                    productEntity.setDefaultProduct(true);
                    map.put("optionIds",goodsProductCopyNew.getVScaleIds());
                }else{
                    productEntity.setDefaultProduct(false);
                }
                productEntity.setTotalPrice(goodsProductCopyNew.getProductPrice());
                productEntity.setExpandPrice(goodsProductCopyNew.getProductLPrice());
                productEntity.setSinglePrice(goodsProductCopyNew.getSinglePrice());
                productEntity.setMarketPrice(goodsProductCopyNew.getMktprice());
                productEntity.setlMarketPrice(goodsProductCopyNew.getSlabMktprice());
                productEntity.setCost(goodsProductCopyNew.getCost());
                productEntity.setlCost(goodsProductCopyNew.getSlabCost());
                productEntity.setProductInfo(goodsProductCopyNew.getSpecInfo());
                productEntity.setWeight(goodsProductCopyNew.getProductWeight());
                productEntity.setStore(new BigDecimal(goodsProductCopyNew.getStore() == null?0:goodsProductCopyNew.getStore()));
                productEntity.setUnit(goodsProductCopyNew.getProductUnit());
                productEntity.setMarketable(goodsProductCopyNew.getProductMarketable());
                productEntity.setOptionIds(goodsProductCopyNew.getVScaleIds());
                productEntity.setCraftOptionIds(goodsProductCopyNew.getVCraftIds());
                productEntity.setCraftPriceId(goodsProductCopyNew.getProductCraftId());
//                productEntity.setDisabled(goodsProductCopyNew.getDisabled() == 1?true:false);
                productEntity.setDisabled(false);
                productEntity.setDateFlag(true);
                goodsProductList.add(productEntity);
            }
        }
        return goodsProductList;
    }

    /**
     * 数据迁移根据商品生产新商品实体
     * @param goodsCopyNewEntity
     * @return
     */
    private GoodsEntity loadGoods(GoodsCopyNewEntity goodsCopyNewEntity) {
        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setGoodsId(goodsCopyNewEntity.getGoodsId());
        goodsEntity.setGoodsNo(goodsCopyNewEntity.getBn());
        goodsEntity.setName(goodsCopyNewEntity.getName());
        goodsEntity.setCategoryId(goodsCopyNewEntity.getCatId());
        goodsEntity.setBrandId(goodsCopyNewEntity.getBrandId());
        //两张图片日后再说
        goodsEntity.setMinBuyNum(new BigDecimal(goodsCopyNewEntity.getMinBuy()==null?0:goodsCopyNewEntity.getMinBuy()));
//        goodsEntity.setGoodsType(goodsCopyNewEntity.getAddcartBuyType());
        switch(goodsCopyNewEntity.getAddcartBuyType()){
            case "normal":
                //购买类型(normal'：普通商品'print'：印刷商品 design_service：设计商品'quote'：报价商品paper'：大纸商品fold：折页template'：索样商品)
                //'商品类型(standard：普通商品),(print：报价-印刷商品),(paper：大纸商品),(fast：报价-快印商品),(material：报价-广告物料),(copy：复印纸)'
                goodsEntity.setGoodsType("standard");
                break;
            case "copy":
                goodsEntity.setGoodsType("copy");
                break;
            case "paper":
                goodsEntity.setGoodsType("paper");
                break;
            case "print":
                goodsEntity.setGoodsType("standard");
                break;
            case "design_service":
                goodsEntity.setGoodsType("design");
                break;
            case "quote":
                goodsEntity.setGoodsType("standard");
                break;
            case "fold":
                goodsEntity.setGoodsType("standard");
                break;
            case "template":
                goodsEntity.setGoodsType("standard");
                break;
            default:
                goodsEntity.setGoodsType("standard");
                break;
        }
        goodsEntity.setOldGoodsType(goodsCopyNewEntity.getAddcartBuyType());
        goodsEntity.setRelateDesignIds(goodsCopyNewEntity.getRelateDesignIds());
        goodsEntity.setKeywords(goodsCopyNewEntity.getKeywords());
        goodsEntity.setFreightId(goodsCopyNewEntity.getFreightid());
        goodsEntity.setSelf(goodsCopyNewEntity.getIsSupplier() ==1?true:false);
        goodsEntity.setSellerId(goodsCopyNewEntity.getSupplierId());
        goodsEntity.setDisabled(false);
        goodsEntity.setIsUnit(goodsCopyNewEntity.getIsUnit());
        goodsEntity.setNoStore(goodsCopyNewEntity.getNostoreSell());
        goodsEntity.setMarketable(goodsCopyNewEntity.getxMarketable());
        goodsEntity.setUnit(goodsCopyNewEntity.getUnit());
        goodsEntity.setBrief(goodsCopyNewEntity.getBrief());
        goodsEntity.setDateFlag(true);
        return goodsEntity;
    }

}
